<template>
  <div class="my_content_container">
    <!-- 骨架屏区域 -->
    <el-skeleton
      style="width: 100%"
      :loading="loading"
      animated
      class="community_article"
    >
      <template slot="template">
        <div class="template_item">
          <el-skeleton-item variant="image" />
          <div class="community_article_item">
            <div class="avatarImage">
              <el-skeleton-item variant="image" />
            </div>
            <div class="community_article_container">
              <div>
                <div class="title">
                  <el-skeleton-item variant="text" style="width: 50%" />
                  <el-skeleton-item
                    variant="text"
                    style="width: 34%; margin-right: 10px"
                  />
                </div>
                <div class="description">
                  <el-skeleton-item variant="text" style="width: 80%" />
                  <el-skeleton-item variant="text" style="width: 30%" />
                </div>
              </div>
            </div>
          </div>
          <div class="content_container">
            <div class="center_list">
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
              <el-skeleton-item variant="text" style="width: 11%" />
            </div>
            <div class="center_content">
              <div>
                <div class="center_content_item">
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                </div>
                <div class="center_content_item">
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                </div>
                <div class="center_content_item">
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                </div>
                <div class="center_content_item">
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-skeleton>
    <div
      class="my_content_container_box"
      :style="loading ? 'display:none;' : 'display:block;'"
    >
      <!-- 用户信息 -->
      <MyAvatar></MyAvatar>
      <!-- 右侧内容展示区 -->
      <div class="my_content_container_end">
        <!-- 左侧侧边栏 -->
        <div class="my_content_container_sidebar">
          <div
            class="sidebar_item"
            @click="toggleActive(item, index)"
            v-for="(item, index) in sidebar"
            :class="{ active: index === active }"
            :key="index"
          >
            <span class="sidebar_item_text text_active2">{{ item.title }}</span>
            <span class="sidebar_item_text text_active">{{
              item.title.slice(2)
            }}</span>
            <span class="icon"><i class="iconfont icon-xiala1"></i></span>
          </div>
        </div>
        <!-- 放置路由组件 -->
        <div class="my_content_container_router">
          <!-- 路由组件 -->
          <el-card v-loading="loadingResource">
            <router-view :key="key"></router-view>
          </el-card>
        </div>
      </div>
      <!-- 返回顶部栏 -->
      <GoBack></GoBack>
    </div>
  </div>
</template>

<script>
import MyAvatar from "./components/Avatar";
import { mapActions, mapState } from "vuex";
import { userAugment } from "@/api/users";
import Message from "@/utils/message";
import { getToken } from "@/utils/auth";
let showMessage = new Message();

export default {
  name: "MyCenter",
  components: {
    MyAvatar,
  },
  computed: {
    ...mapState("user", ["aimUserInfo", "userInfo"]),
    key() {
      // 获取目标用户信息
      this.$store
        .dispatch("user/aimUserInfo", this.$route.params.id)
        .then(() => {
          this.loading = false;
        });
      // 当切换成别人的个人中心时
      if (this.$route.params.id !== this.aimId) {
        this.aimId = this.$route.params.id;
        this.active = 0;
        this.$router.push(`/center/${this.aimId}/info`);
      }
      // 当切换成别人的个人中心时
      if (!/info|material/.test(this.$route.path)) {
        // 开启加载资源loading
        this.loadingResource = true;
      } else {
        this.loadingResource = false;
      }
      this.handlerIndex();
      return this.$route.name !== undefined
        ? this.$route.name + new Date()
        : this.$route + new Date();
    },
  },
  data() {
    return {
      // 侧边栏内容
      sidebar: [
        {
          title: "信息概况",
          url: `/center/:id/info`,
        },
        {
          title: "个人资料",
          url: `/center/:id/material`,
        },
        {
          title: "相关文章",
          url: `/center/:id/article`,
        },
        {
          title: "我的关注",
          url: `/center/:id/concern`,
        },
        {
          title: "我的粉丝",
          url: "/center/:id/fans",
        },
        {
          title: "我的收藏",
          url: "/center/:id/collect",
        },
        {
          title: "浏览历史",
          url: "/center/:id/history",
        },
      ],
      // 当前选中的内容
      active: 0,
      // 当前paramsId
      aimId: this.$route.params.id,
      // 骨架屏
      loading: true,
      // 加载资源
      loadingResource: false,
    };
  },
  methods: {
    ...mapActions("user", {
      updateUserInfo: "updateUserInfo",
    }),
    // 更改Active下标
    toggleActive(item, index) {
      this.$router.replace(item.url.replace(":id", this.$route.params.id));
      this.active = index;
    },
    // 发起文章收藏浏览评论相关请求
    toolRequest(flag, choice, id, selfId) {
      /**
       * @params flag 决定哪个数据类型的增减
       * @params choice 是增加还是减少 0加 1减
       *
       * @return Promise 对象
       */
      if (!getToken()) {
        showMessage.error({
          message: "只有登录后才能使用哦😋",
          type: "error",
          duration: 5 * 1000,
          offset: 80,
        });
        return new Promise(() => {});
      }

      return new Promise(async (resolve, reject) => {
        const reqArr = ["agree", "collect", "browse", "concern", "fans"];
        let reqIndex = -1;

        // 确定传入参数
        switch (flag) {
          case "guan":
            reqIndex = 3;
            break;
          case "fen":
            reqIndex = 4;
            break;
        }
        if (reqIndex !== -1) {
          // 提取出要指定的数据名
          let attr = reqArr[reqIndex];

          // 开始更新指定数据
          // 初始内容为空则初始化数据
          // 初始内容不为空则将其解码为正常对象

          let newValue = null;

          // 如果删除粉丝的数量，则需要从对方的用户信息上获取
          if (reqIndex === 4) {
            newValue = !this.aimUserInfo[attr]
              ? { content: [] }
              : JSON.parse(this.aimUserInfo[attr]);
          } else {
            newValue = !this.userInfo[attr]
              ? { content: [] }
              : JSON.parse(this.userInfo[attr]);
          }
          let newObj = { content: [] };

          // 确定是增加还是删除该指定内容数据
          if (choice) {
            // 删除，判断是删除用户id还是文章id
            if (reqIndex === 3 || reqIndex === 4) {
              newObj.content = newValue.content.filter((item) => {
                if (item !== id) return item;
              });
            } else {
              newObj.content = newValue.content.filter((item) => {
                if (item !== this.newArticleData.article_id) return item;
              });
            }
          } else {
            // 增加，判断是增加用户id还是文章id
            if (reqIndex === 3 || reqIndex === 4) {
              newObj.content = [...new Set([...newValue.content, id])];
            } else {
              newObj.content = [
                ...new Set([
                  ...newValue.content,
                  this.newArticleData.article_id,
                ]),
              ];
            }
          }

          try {
            // 增加用户指定数据，如粉丝，关注，点赞等等
            let result = await userAugment(
              "6",
              selfId,
              `${attr}~${JSON.stringify(newObj)}`
            );
            if (result.code != 200 && result.code != 401)
              reject(result.message);

            // 更新全局用户信息
            await this.updateUserInfo();
            await this.$store.dispatch(
              "user/aimUserInfo",
              this.$route.params.id
            );
            resolve("ok");

            // 如果点击的是关注，则接着触发增加该作者粉丝
            if (reqIndex === 3) {
              this.toolRequest("fen", choice, selfId, id).catch((err) => {
                this.$win(err, "error");
              });
            }
          } catch (error) {
            reject(error);
          }
        }
      });
    },
    // 重新设置index
    handlerIndex() {
      this.sidebar.forEach((item, i) => {
        if (this.$route.path.indexOf(item.path) !== -1) {
          console.log(i);
          this.active = i;
        }
      });
    },
  },
  mounted() {
    this.handlerIndex();
    // 获取目标用户信息
    this.$store.dispatch("user/aimUserInfo", this.$route.params.id).then(() => {
      this.loading = false;
    });
  },
};
</script>

<style lang="less" scoped>
.my_content_container {
  padding-top: 26px;
  /deep/ .el-card {
    .empty {
      padding-top: 20px;
    }
  }
  /deep/ .el-skeleton {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
    .template_item {
      padding: 0;
      border: 0 !important;
      padding-bottom: 10px;
    }
    .el-skeleton__image {
      width: 100%;
      height: 140px;
    }
    .community_article_item {
      .el-skeleton__image {
        width: 72px !important;
        height: 72px !important;
        border-radius: 50%;
        margin-left: 10px;
      }
    }
    .community_article_container {
      padding-top: 6px;
      .title {
        display: flex;
        justify-content: space-between;
        .el-skeleton__text {
          height: 16px !important;
        }
      }
      .description {
        margin-top: 12px;
        display: flex;
        flex-direction: column;
        .el-skeleton__item {
          margin-bottom: 6px;
        }
      }
    }
    .center_list {
      display: flex;
      justify-content: space-between;
      padding: 42px 10px 0;
    }
    .center_content {
      padding: 26px 10px;
      & > div {
        & > div {
          display: flex;
        }
      }
      & > div {
        .el-skeleton__item {
          height: 18px !important;
          margin-bottom: 12px;
          &:first-of-type {
            width: 20%;
            margin-right: 14px;
          }
        }
      }
    }
  }
  .my_content_container_end {
    max-width: 1200px;
    margin: 0 auto;
    position: relative;
    .my_content_container_sidebar {
      position: absolute;
      width: 220px;
      background: #fff;
      padding: 8px 0;
      .sidebar_item {
        height: 56px;
        line-height: 56px;
        cursor: url("@/assets/mouse/x2.cur"), auto !important;
        font-size: 15px;
        text-align: left;
        padding: 0 34px;
        background: #fff;
        color: #505050;
        border-bottom: var(--main-border-bottom);
        display: flex;
        justify-content: space-between;
        .icon {
          transform: rotate(-90deg);
        }
        &.active {
          color: var(--a-button-hover-color);
        }
      }
    }
    .my_content_container_router {
      margin-left: 240px;
      min-height: 700px;
      /deep/ .el-card {
        border: none;
        box-shadow: none;
        min-height: 200px;
        .el-card__body {
          padding: 0;
        }
      }
    }
  }
  .text_active {
    display: none;
  }
  .text_active2 {
    display: block;
  }
}
</style>